﻿using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Text;
using System.Drawing;
using System.Threading;
using System.Reflection;
using System.Configuration;
using System.ComponentModel;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using DevComponents.DotNetBar;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.IO;
using PlanningGIS.Framework;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Util;
using PlanningGIS.ArcGIS;
using PlanningGIS.Util.Log;
using PlanningGIS.Util.Arithmetic;
using PlanningGIS.Engine.Controls;
using PlanningGIS.ManageUtility;
using PlanningGIS.Framework.Config;
using PlanningGIS.ManageUtility.Modules;

namespace PlanningGIS.Entry
{
    /// <summary>
    /// 作用：系统主界面
    /// </summary>
    public partial class MainFramework : Office2007RibbonForm, IMessageFilter
    {
        #region User Define
        /// <summary>
        /// 应用程序窗体
        /// </summary>
        IApplication _Application = new ApplicationClass();  
      
        /// <summary>
        /// 结果分页控件
        /// </summary>
        private PlanningGIS.Framework.Controls.PagedGrid pagedGrid1;

        /// <summary>
        /// 日志控件
        /// </summary>
        private PlanningGIS.Win.Controls.LogPanel logPanel1;

        /// <summary>
        /// 结果列表控件
        /// </summary>
        private PlanningGIS.Engine.Controls.RecordList recordList1;      
  
        /// <summary>
        /// 鹰眼控件
        /// </summary>
        private PlanningGIS.Framework.Controls.OverViewPanel overViewPanel1;

        /// <summary>
        /// 自定义图层列表控件
        /// </summary>
        private PlanningGIS.Framework.Controls.CustomTOCControl customTOCControl1;
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="hwnd"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern long SetCapture(int hwnd);

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern long ReleaseCapture();

        /// <summary>
        /// 
        /// </summary>
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

        /// <summary>
        /// 
        /// </summary>
        private readonly string BOTTOMHIDE = AppConfig.ConfigPath + "\\hidetemp";        
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public MainFramework()
        {
            this.Visible = false;
            AppConfig.IsRunLocal = ConfigurationManager.AppSettings.Get("单机运行").Equals("true", StringComparison.CurrentCultureIgnoreCase);
            FrameworkHelper.SysName = ConfigurationManager.AppSettings.Get("SysName");
            if (AppConfig.IsRunLocal)
            {
                string strFile = Application.StartupPath + "\\规划地理信息系统.xml";
                if (!File.Exists(strFile))
                {
                    MsgHelper.ShowInfomationMsgbox("系统配置文件【" + strFile + "】文件不存在！");
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                    return;
                }
                FrameworkHelper.CurrentUser = new ManageUtility.Modules.User()
                {
                    Login_Name = ManageHelper.Administrator,
                    Name = "单机版用户"
                };
                XmlDocument doc = new XmlDocument();
                doc.Load(strFile);
                PrivilegeGroup rolecontent = new PrivilegeGroup();
                rolecontent.Xml = doc.InnerXml;
                List<IPrivilegeGroup> group = new List<IPrivilegeGroup>();
                foreach (IPrivilegeElement element in rolecontent.GetChilds())
                {
                    if (element is IPrivilegeGroup)
                    {
                        group.Add(element as IPrivilegeGroup);
                    }
                }
                FrameworkHelper.CurrentUser.MenuContents = group;

                doc = new XmlDocument();
                doc.Load(AppConfig.StartupPath + "\\tocmenuconfig.xml");
                rolecontent = new PrivilegeGroup();
                rolecontent.Xml = doc.InnerXml;

                List<IPrivilegeGroup> tocMenugroup = new List<IPrivilegeGroup>();
                foreach (IPrivilegeElement element in rolecontent.GetChilds())
                {
                    if (element is IPrivilegeGroup)
                    {
                        tocMenugroup.Add(element as IPrivilegeGroup);
                    }
                }
                FrameworkHelper.CurrentUser.TocContents = tocMenugroup;
            }
            else
            {
                ManageHelper.DBContext = DbConnectHelper.CreateDbContextByIntance("MT");
                FrmLogin frm = new FrmLogin();
                if (frm.ShowDialog() != DialogResult.OK)
                {
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                    return;
                }
                FrameworkHelper.CurrentUser.InitData();
            }
            this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
            this.UpdateStyles();
            Thread.Sleep(100);
            Thread splashthread = new Thread(new ThreadStart(SplashScreen.ShowSplashScreen));
            splashthread.IsBackground = true;
            splashthread.Start();
            InitializeComponent();
            Text = FrameworkHelper.SysName;
            FrameworkHelper.AxMapControl = this.m_MapControl;
            AoHelper.StylePath = AppConfig.StylePath;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            try
            {
                base.WndProc(ref m);
                if (m.Msg == 0x231)
                {
                    m_MapControl.SuppressResizeDrawing(true, 0);
                }
                else if (m.Msg == 0x232)
                {
                    m_MapControl.SuppressResizeDrawing(false, 0);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorText(ex);
            }            
        }

        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender1"></param>
        /// <param name="e1"></param>
        void MainFramework_Load(object sender1, System.EventArgs e1)
        {
            this.Invoke(new Action(delegate { FrameworkHelper.InitParam(); }));
            LogHelper.WriteLogEvent = WriteLog;
            RecordListHelper.AddRecordItemEvent = AddRecordItem;
            RecordListHelper.AddRecordItemEvent2 = AddRecordItem2;            
            FrameworkHelper.ShowLogPanelEvent = ShowLogPanel;
            FrameworkHelper.ShowRecordListEvent = ShowRecordPanel;
            FrameworkHelper.RefreshMapEvent = RefreshMap;
            FrameworkHelper.RefreshTocEvent = RefreshToc;
            SystemInitialize();
            recordList1.FocusMap = m_MapControl.Map;
            RecordListHelper.RecordCtl = recordList1;
            ShowUserInfo();
            MsgHelper.OWNER  = this;

        }

        /// <summary>
        /// 
        /// </summary>
        FrmSecurity frmSecurity = null;
        /// <summary>
        /// 开始停止操作的时间
        /// </summary>
        DateTime stopTime = DateTime.Now;
        /// <summary>
        /// 
        /// </summary>
        IntPtr opptr = new IntPtr(0);

        /// <summary>
        /// 显示登录的用户信息
        /// </summary>
        private void ShowUserInfo()
        {
            if (FrameworkHelper.CurrentUser.IsAdministrator()) return;
            try
            {
                if (ManageHelper.SecuritySet.IdentifyTime > 0)
                {
                    Application.AddMessageFilter(this);
                    timer1.Start();
                    stopTime = DateTime.Now;
                }
                if (ManageHelper.SecuritySet.ShowSecurity)
                {
                    frmSecurity = new FrmSecurity();
                    SetSecurityLoaction();
                    frmSecurity.Show(this);
                }
                if (ManageHelper.SecuritySet.PasswordValid > 0)
                {
                    DateTime tm = FrameworkHelper.CurrentUser.EffectiveTime.AddMonths(ManageHelper.SecuritySet.PasswordValid);
                    lblPsdMsg.Text = string.Format("您的密码将于{0}失效，请及时修改密码！", tm.ToShortDateString());
                }
            }
            catch 
            {

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool PreFilterMessage(ref System.Windows.Forms.Message m)
        {
            //如果检测到有鼠标或则键盘的消息，则使计数为0.....  m.Msg == 0x0200 ||
            if (m.Msg == 0x0200) //由于鼠标停留和鼠标滚动的值是一样的，故需要单独判断
            {
                if (opptr.ToInt32() != m.LParam.ToInt32())//鼠标停留时LParam的值是最后一次移动后的值，移动时LParam的每次都不一样
                {
                    stopTime = DateTime.Now;
                    opptr = m.LParam;
                }
            }
            else if (m.Msg == 0x0201 || m.Msg == 0x0204 || m.Msg == 0x0207 || m.Msg == 0X0100)
            {
                stopTime = DateTime.Now;
            }
            return false;
        }
        
        /// <summary>
        /// 自动直接退出
        /// </summary>
        private bool _autoExit = false;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (stopTime.AddMinutes(ManageHelper.SecuritySet.IdentifyTime) < DateTime.Now)
            {
                _autoExit = false;
                timer1.Stop();
                stopTime = DateTime.Now;
                FrmReLogin frm = new FrmReLogin();
                frm.FormClosed += frm_FormClosed;
                if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {                   
                    timer1.Start();
                    stopTime = DateTime.Now;
                }
                else
                {
                    _autoExit = true;
                    Application.Exit();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void frm_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void SystemInitialize()
        {
            this.Hide();
            try
            {
                (_Application as IApplicationEvents).MapChanged += new MapChangedEventHandler(MainFramework_MapChanged);
                #region 控件初始化
                // 
                // customTOCControl1
                // 
                this.customTOCControl1 = new PlanningGIS.Framework.Controls.CustomTOCControl();
                this.customTOCControl1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.customTOCControl1.Location = new System.Drawing.Point(0, 0);
                this.customTOCControl1.Name = "customTOCControl1";
                this.customTOCControl1.TabIndex = 0;
                this.dockPanelToc.Controls.Add(this.customTOCControl1);
                // 
                // pagedGrid1
                // 
                this.pagedGrid1 = new PlanningGIS.Framework.Controls.PagedGrid();
                this.pagedGrid1.DataQuery = null;
                this.pagedGrid1.DataUpdate = null;
                this.pagedGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.pagedGrid1.Location = new System.Drawing.Point(0, 0);
                this.pagedGrid1.Name = "pagedGrid1";
                this.pagedGrid1.RowClick = null;
                this.pagedGrid1.RowDblClick = null;
                this.pagedGrid1.TabIndex = 1;
                this.pagedGrid1.Turnpage = null;
                this.dockPanelList.Controls.Add(this.pagedGrid1);


                // 
                // logPanel1
                // 
                this.logPanel1 = new LogPanel();
                this.logPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.logPanel1.Location = new System.Drawing.Point(0, 0);
                this.logPanel1.Name = "日志";
                this.logPanel1.TabIndex = 1;
                this.dockPanelLog.Controls.Add(this.logPanel1);

                this.recordList1 = new Engine.Controls.RecordList();
                this.recordList1.Dock = DockStyle.Fill;
                this.recordList1.Location = new System.Drawing.Point(0, 0);
                this.recordList1.Name = "结果列表";
                this.recordList1.TabIndex = 2;
                this.dockPanelRecord.Controls.Add(this.recordList1);

                // 
                // overViewPanel1
                // 
                this.overViewPanel1 = new PlanningGIS.Framework.Controls.OverViewPanel();
                this.overViewPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.overViewPanel1.Location = new System.Drawing.Point(0, 0);
                this.overViewPanel1.MapControl = null;
                this.overViewPanel1.Name = "overViewPanel1";
                this.overViewPanel1.Size = new System.Drawing.Size(251, 273);
                this.overViewPanel1.TabIndex = 0;
                this.dockPanelOverview.Controls.Add(this.overViewPanel1);

                #endregion
                
                #region BarManager
                lblUser.Text = "当前用户：" + FrameworkHelper.CurrentUser.Name;
                FrameworkHelper.MdiForm = this;
                this.tabControl1.SelectedTabChanged += new TabStrip.SelectedTabChangedEventHandler(tabControl1_SelectedTabChanged);
                (_Application as IFramework).DockManager.DockManager = this.dotNetBarManager1;
                this.customTOCControl1.Applicatoin = _Application;
                (_Application as IFramework).TOCControl = this.customTOCControl1.TOCControl.Object as ITOCControl2;
                (_Application as IFramework).BindControls(this.m_MapControl.Object as IMapControl3, this.m_PageLayoutControl.Object as IPageLayoutControl2, this.m_SceneControl.Object as ISceneControl, true);
                (_Application as IFramework).BarManager.CommandPoolEx.Hook = _Application;
                _Application.StatusBar.StatusBar = this.barStauts;
                (_Application as IFramework).BarManager.OnItemClickEvent += new OnItemClickEventHandler(BarManager_OnItemClickEvent);
                (_Application as IFramework).BarManager.CreateBar(ribbonControl1, FrameworkHelper.CurrentUser.MenuContents, _Application);
                (_Application as IFramework).MdiForm = this;

                #endregion

                #region 地图事件
                m_MapControl.OnBeforeScreenDraw += delegate { ShowWorkingStatus(true); };
                m_MapControl.OnAfterScreenDraw += delegate { ShowWorkingStatus(false); };
                m_MapControl.OnMouseDown += new IMapControlEvents2_Ax_OnMouseDownEventHandler(m_MapControl_OnMouseDown);
                m_PageLayoutControl.OnMouseDown += new IPageLayoutControlEvents_Ax_OnMouseDownEventHandler(m_PageLayoutControl_OnMouseDown);
                m_MapControl.OnKeyDown += new IMapControlEvents2_Ax_OnKeyDownEventHandler(m_MapControl_OnKeyDown);
                m_MapControl.OnMouseMove += m_MapControl_OnMouseMove;
                #endregion

                LoadUserData();
                ReadLayoutConfig();

                #region 设置风格
                string strStyle = System.Configuration.ConfigurationManager.AppSettings.Get("SystemStyle");
                if (strStyle != null && strStyle.Trim() != "")
                {
                    bool bln = Enum.IsDefined(typeof(eStyle), strStyle.Trim());
                    if (bln)
                    {
                        eStyle style = (eStyle)Enum.Parse(typeof(eStyle), strStyle.Trim());
                        StyleManager.ChangeStyle(style, Color.Empty);
                        foreach (ButtonItem item in btnChangeStyle.SubItems)
                        {
                            if (item.CommandParameter.ToString() == strStyle)
                            {
                                item.Checked = true;
                                break;
                            }
                        }
                    }
                }
                #endregion

                FrameworkHelper.MainMap = m_MapControl.Map;
                FrameworkHelper._Application = _Application;
                SplashScreen.CloseSplashScreen();
                this.Visible = true;
                this.WindowState = FormWindowState.Maximized;
                Thread.Sleep(100);
                string sMxdFile = AppConfig.DataPath + "\\背景图.mxd";
                this._Application.OpenDocument(sMxdFile);
                overViewPanel1.MapControl = this.m_MapControl.Object as IMapControl3;
                Thread t = new Thread(ThreadProc);
                t.Start();
            }
            catch (Exception ex)
            {
                SplashScreen.CloseSplashScreen();
                this.Visible = true;
                MsgHelper.ShowInfomationMsgbox("系统初始化出现错误，错误信息:" + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_MapControl_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            int precision = AppConfig.SystemConfig.基本信息.数值显示精度;
            if (precision <= 0) precision = 2;
            if (m_MapControl.SpatialReference is IGeographicCoordinateSystem)
            {
                string longitude = CoordSystemHelper.DEG2DMS(e.mapX, 0);
                string latitude = CoordSystemHelper.DEG2DMS(e.mapY, 0);
                SetCurrentCoords(string.Format("经度：{0:F}，纬度：{1:F} ", longitude, latitude));
            }
            else if (m_MapControl.SpatialReference is IProjectedCoordinateSystem)
            {
                string str = string.Format("X:{0:F}，Y:{1:F}  " + Convertor.esriUnit2Chinese(esriUnits.esriMeters), e.mapX.ToString("F" + precision), e.mapY.ToString("F" + precision));
                SetCurrentCoords(str);
            }
            else
            {
                string str = string.Format("X:{0:F}，Y:{1:F}  " + Convertor.esriUnit2Chinese(esriUnits.esriUnknownUnits), e.mapX.ToString("F" + precision), e.mapY.ToString("F" + precision));
                SetCurrentCoords(str);
            }
        }


        /// <summary>
        /// 在数据库模式下加载用户有权限的信息
        /// </summary>
        private void LoadUserData()
        {
            mnuPSD.Visible = !AppConfig.IsRunLocal;
            mnuUpUser.Visible = !AppConfig.IsRunLocal;
            dockItemResource.Visible = !AppConfig.IsRunLocal;
            btnMxd.Visible = !AppConfig.IsRunLocal;
            if (!AppConfig.IsRunLocal)           
            {
                try
                {
                    resourceTree1.MapControl = (IMapControl2)(m_MapControl.Object);
                    resourceTree1.CheckWithin = true;
                    resourceTree1.BindData();
                    List<MXDInfo> mxds = FrameworkHelper.CurrentUser.GetMxdInfos();
                    if (mxds != null && mxds.Count > 0)
                    {
                        foreach (MXDInfo m in mxds)
                        {
                            ButtonItem btnItm = new ButtonItem(m.ID);
                            btnItm.Text = m.Name;
                            btnItm.Tag = m.Content;
                            btnItm.Click += btnMxd_Click;
                            btnMxd.SubItems.Add(btnItm);
                        }
                    }
                }
                catch
                {
                    
                }      
            }

        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnMxd_Click(object sender, EventArgs e)
        {
            try
            {
                ButtonItem btn = (ButtonItem)sender;
                if (btn.Tag == null) return;
                string fpath = AppConfig.StartupPath + "\\Temp\\Mxd";
                if (!Directory.Exists(fpath)) Directory.CreateDirectory(fpath);
                fpath = fpath + "\\" + btn.Text + ".mxd";
                if (!File.Exists(fpath))
                {
                    FileHelper.WriteFile(fpath, (byte[])btn.Tag);
                    Application.DoEvents();
                }
                if (File.Exists(fpath))
                {
                    m_MapControl.LoadMxFile(fpath);
                    //Log.WriteLog(FrameworkHelper.CurrentUser.Name, Log.zjgisLogType.AccessMxd, Log.zjgisLogStatus.Success, btn.Text);
                }
            }
            catch 
            {
                
            }
            
        }


        /// <summary>
        /// 地图改变事件
        /// </summary>
        /// <param name="map"></param>
        void MainFramework_MapChanged(IMap map)
        {
            recordList1.FocusMap = m_MapControl.Map;
            FrameworkHelper.MainMap = m_MapControl.Map;
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="msg"></param>
        private void WriteLog(dynamic msg)
        {
            if (logPanel1 == null) return;
            try
            {
                if (logPanel1.InvokeRequired)
                {
                    WriteLog2 d = new WriteLog2(WriteLog);
                    logPanel1.Invoke(d, new object[] { msg });
                }
                else
                {
                    logPanel1.WriteLog(msg);
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 显示日志面板
        /// </summary>
        private void ShowLogPanel()
        {
            if (barBottom.InvokeRequired)
            {
                InvokeEventHandler ivk = new InvokeEventHandler(ShowLogPanel);
                barBottom.Invoke(ivk);
            }
            else
            {
                dockItemLog.Visible = true;
                barBottom.SelectedDockContainerItem = dockItemLog;
                barBottom.Visible = true;
            }
        }

        /// <summary>
        /// 添加记录到列表中
        /// </summary>
        /// <param name="errType">类型</param>
        /// <param name="featLyr1">空间对象数据集1</param>
        /// <param name="featLyr2">空间对象数据集2</param>
        /// <param name="feat1">空间对象1</param>
        /// <param name="feat2">空间对象2</param>
        /// <param name="geometry">范围</param>
        /// <param name="remark">备注</param>
        private void AddRecordItem(string errType, IFeatureLayer featLyr1, IFeatureLayer featLyr2, IFeature feat1, IFeature feat2, IGeometry geometry, string remark)
        {
            if (recordList1 == null) return;
            try
            {
                if (recordList1.InvokeRequired)
                {
                    RecordItem d = new RecordItem(AddRecordItem);
                    recordList1.Invoke(d, errType, featLyr1, featLyr2, feat1, feat2, geometry, remark);
                }
                else
                {
                    recordList1.addErr2Grid(errType, featLyr1, featLyr2, feat1, feat2, geometry, remark);                    
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 添加记录到列表中
        /// </summary>
        /// <param name="errType">类型</param>
        /// <param name="featLyr1">空间对象数据集1</param>
        /// <param name="featLyr2">空间对象数据集2</param>
        /// <param name="oid1">空间对象索引1</param>
        /// <param name="oid2">空间对象索引2</param>
        /// <param name="geometry">范围</param>
        /// <param name="remark">备注</param>
        private void AddRecordItem2(string errType, IFeatureLayer featLyr1, IFeatureLayer featLyr2, int oid1, int oid2, IGeometry geometry, string remark)
        {
            if (recordList1 == null) return;
            try
            {
                if (recordList1.InvokeRequired)
                {
                    RecordItem2 d = new RecordItem2(AddRecordItem2);
                    recordList1.Invoke(d, errType, featLyr1, featLyr2, oid1, oid2, geometry, remark);
                }
                else
                {
                    recordList1.addErr2Grid(errType, featLyr1, featLyr2, oid1, oid2, geometry, remark);
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 显示结果面板
        /// </summary>
        private void ShowRecordPanel()
        {
            if (barBottom.InvokeRequired)
            {
                InvokeEventHandler ivk = new InvokeEventHandler(ShowRecordPanel);
                barBottom.Invoke(ivk);
            }
            else
            {
                dockItemRecord.Visible = true;
                barBottom.SelectedDockContainerItem = dockItemRecord;
                barBottom.Visible = true;
            }
        }

        /// <summary>
        /// 刷新地图
        /// </summary>
        private void RefreshMap()
        {
            if ((_Application as IFramework).IsMapCtrlactive)
            {
                m_MapControl.Refresh();
            }
            else if ((_Application as IFramework).IsPageLayoutActive)
            {
                m_PageLayoutControl.Refresh();
            }
        }

        /// <summary>
        /// 刷新图层树
        /// </summary>
        private void RefreshToc()
        {
            customTOCControl1.RefreshToc();
        }

        /// <summary>
        /// 地图键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_MapControl_OnKeyDown(object sender, IMapControlEvents2_OnKeyDownEvent e)
        {

        }

        /// <summary>
        /// 地图鼠标事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_MapControl_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            m_MapControl.Focus();
            if (e.button == 2)
                (_Application as IFramework).BarManager.GetContextMenuStrip(_Application, e.x, e.y);
            if (e.button == 4)
            {
                m_MapControl.MousePointer = esriControlsMousePointer.esriPointerPanning;
                m_MapControl.Pan();
                m_MapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
            }
        }

        /// <summary>
        /// 布局鼠标事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_PageLayoutControl_OnMouseDown(object sender, IPageLayoutControlEvents_OnMouseDownEvent e)
        {
            m_PageLayoutControl.Focus();
            if (e.button == 2)
                (_Application as IFramework).BarManager.GetContextMenuStrip(_Application, e.x, e.y);
            if (e.button == 4)
            {
                m_PageLayoutControl.MousePointer = esriControlsMousePointer.esriPointerPanning;
                m_PageLayoutControl.Pan();
                m_PageLayoutControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
            }
        }

        /// <summary>
        /// 执行线程操作
        /// </summary>
        public void ThreadProc()
        {
            try
            {
                #region 网络监控
                //if (myClient != null)
                //{
                //    try
                //    {
                //        if (myClient.ISConnect)
                //            myClient.Connect();
                //    }
                //    catch
                //    {
                //        ;
                //    }
                //}
                #endregion

                timer.Tick += delegate(object sender, EventArgs e)
                {

                    timer.Stop();
                    (_Application as IFramework).BarManager.CommandPoolEx.UpdateCommandState();
                    //if (myClient != null && myClient.ISConnect)
                    //    myClient.Connect();
                    timer.Start();
                };
                timer.Interval = 500;
                timer.Start();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorText(ex.Message);
            }
        }

        /// <summary>
        /// 点击按钮
        /// </summary>
        /// <param name="obj"></param>
        void BarManager_OnItemClickEvent(object obj)
        {
            (_Application as IFramework).ExecuteCommand(obj as ESRI.ArcGIS.SystemUI.ICommand);
        }

        /// <summary>
        /// 显示坐标
        /// </summary>
        /// <param name="text"></param>
        public void SetCurrentCoords(string text)
        {
            lblCoordinate.Text = text;
        }

        /// <summary>
        /// 显示经度条
        /// </summary>
        /// <param name="isWorking"></param>
        public void ShowWorkingStatus(bool isWorking)
        {
            try
            {
                if (isWorking)
                {
                    timer.Stop();
                    _Application.StatusBar.ShowProgressBar("");
                }
                else
                {
                    timer.Start();
                    _Application.StatusBar.HideProgressBar();
                }
            }
            catch(Exception ex)
            {
                LogHelper.WriteErrorText(ex);
            }
        }

        /// <summary>
        /// Tab选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_SelectedTabChanged(object sender, TabStripTabChangedEventArgs e)
        {
            timer.Stop();
            this.Cursor = Cursors.WaitCursor;
            switch (this.tabControl1.SelectedTabIndex)
            {
                case 0:
                    (_Application as IFramework).ActivateMapControl();
                    timer.Start();
                    break;
                case 1:
                    (_Application as IFramework).ActivatePageLayoutControl();
                    timer.Start();
                    break;
                case 2:
                    (_Application as IFramework).ActivateSceneControl();
                    timer.Start();
                    break;
                default:
                    break;
            }
            (_Application as IFramework).RaiseMapPageSwitchEvent();
            this.Cursor = Cursors.Default;
        }
        
        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="e"></param>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (!_autoExit)
            {
                if (MsgHelper.ShowYesOrNoQueryMsgBox("您确定要退出系统吗？") != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }            
            try
            {
                base.OnFormClosing(e);
                timer.Stop();
                if (barBottom.AutoHide)
                {
                    if (!File.Exists(BOTTOMHIDE)) File.Create(BOTTOMHIDE);
                }
                else
                {
                    if (File.Exists(BOTTOMHIDE)) File.Delete(BOTTOMHIDE);
                }

                IEngineEditor m_engineEditor = new EngineEditorClass();
                if (m_engineEditor.EditState == esriEngineEditState.esriEngineStateEditing && m_engineEditor.HasEdits())
                {
                    DialogResult result = MsgHelper.ShowYesOrNoQueryMsgBox("是否保存编辑？");
                    if (result == DialogResult.Yes)
                        m_engineEditor.StopEditing(true);
                    else if (result == DialogResult.No)
                        m_engineEditor.StopEditing(false);
                }
                IMxDocument pMxDocment = (_Application as ApplicationClass).MxDocument;
                if (pMxDocment != null && pMxDocment.FocusMap != null && pMxDocment.FocusMap.LayerCount > 0)
                {
                    IMapDocument pMapDocment = (pMxDocment as MxDocumentClass).MapDocument;
                    if (pMapDocment != null)
                    {
                        DialogResult dr = DialogResult.Cancel;
                        try
                        {
                            if (pMapDocment.DocumentFilename == "")
                            {
                                dr = MsgHelper.ShowYesOrNoQueryMsgBox("是否需要保存当前模板？");
                                if (dr == DialogResult.Yes)
                                {
                                    SaveAsMxd saveAsMxd = new SaveAsMxd();
                                    saveAsMxd.OnCreate(_Application);
                                    saveAsMxd.OnClick();
                                }
                            }
                            else
                            {
                                dr = MsgHelper.ShowYesOrNoQueryMsgBox("是否需要保存‘" + pMapDocment.DocumentFilename + "’？");
                                if (dr == DialogResult.Yes)
                                {
                                    _Application.SaveDocument("");
                                }
                            }
                        }
                        catch
                        {
                            dr = MsgHelper.ShowYesOrNoQueryMsgBox("是否需要保存当前模板？");
                            if (dr == DialogResult.Yes)
                            {
                                SaveAsMxd saveAsMxd = new SaveAsMxd();
                                saveAsMxd.OnCreate(_Application);
                                saveAsMxd.OnClick();

                            }
                        }
                        if (dr == DialogResult.Cancel)
                        {
                            e.Cancel = true;
                            return;
                        }
                    }
                }
                SaveLayoutConfig();
                _Application.Shutdown();
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorText(ex);
            }
        }
        
        /// <summary>
        /// 执行按钮操作事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AppCommandTheme_Executed(object sender, EventArgs e)
        {
            ICommandSource source = sender as ICommandSource;
            if (source.CommandParameter is string)
            {
                eStyle style = (eStyle)Enum.Parse(typeof(eStyle), source.CommandParameter.ToString());
                StyleManager.ChangeStyle(style, Color.Empty);
                System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                if (config.AppSettings.Settings["SystemStyle"] != null)
                {
                    config.AppSettings.Settings["SystemStyle"].Value = source.CommandParameter.ToString();
                    config.Save(System.Configuration.ConfigurationSaveMode.Modified);
                }
            }
            else if (source.CommandParameter is Color)
            {
                StyleManager.ColorTint = (Color)source.CommandParameter;
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 关于
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAbout_Click(object sender, EventArgs e)
        {
            FrmAbout frm = new FrmAbout();
            frm.ShowDialog(this);
        }

        /// <summary>
        /// 帮助
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHelp_Click(object sender, EventArgs e)
        {
            string filePath = Application.StartupPath + "\\Help\\" + "用户手册.pdf";
            if (File.Exists(filePath))
            {
                try
                {
                    System.Diagnostics.Process.Start(filePath);
                }
                catch
                {
                    MsgHelper.ShowInfomationMsgbox("找不到PDF文件的关联程序，无法打开！/n请安装Adobe Arcobat");
                }
            }
            else
            {
                MsgHelper.ShowInfomationMsgbox("找不到帮助文件!");
            }
        }

        /// <summary>
        /// 系统设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetting_Click(object sender, EventArgs e)
        {
            FrmSetting frmSetting = new FrmSetting(_Application);
            frmSetting.ShowDialog(this);
        }

        /// <summary>
        /// 读取快速布局
        /// </summary>
        private void ReadLayoutConfig()
        {
            string strFile = AppConfig.ConfigPath + "\\LayoutConfig.xml";
            if (File.Exists(strFile) == false) return;
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(strFile);
                XmlNode node = doc.SelectSingleNode("//SelectedTabItem");
                if (node != null)
                {
                    for (int i = 0; i < ribbonControl1.Items.Count; i++)
                    {
                        RibbonTabItem item = ribbonControl1.Items[i] as RibbonTabItem;
                        if (item.Text == node.InnerText)
                        {
                            item.Checked = true;
                            break;
                        }
                    }
                }
                int index = 1;
                node = doc.SelectSingleNode("//QuickAccessItems");
                if (node == null) return;
                XmlNodeList nodelist = node.ChildNodes;
                foreach (XmlElement subNode in nodelist)
                {
                    if (subNode.Name == "功能点")
                    {
                        Type elementType = Type.GetType(subNode.Attributes["typename"].Value);
                        if (elementType == null) continue;
                        object elementObj = Activator.CreateInstance(elementType);
                        BaseItem item = (_Application as IFramework).BarManager.CommandPoolEx.FindBaseItem(elementObj.ToString());
                        if (item == null) continue;
                        if (item is ButtonItem)
                        {
                            BaseItem item2 = item.Copy();
                            (item2 as ButtonItem).ButtonStyle = DevComponents.DotNetBar.eButtonStyle.Default;
                            (item2 as ButtonItem).ImagePosition = DevComponents.DotNetBar.eImagePosition.Left;
                            (item2 as ButtonItem).ImageFixedSize = new Size(18, 18);
                            ribbonControl1.QuickToolbarItems.Add(item2);
                            item2.KeyTips = index.ToString();
                            index++;
                        }
                    }
                    else if (subNode.Name == "菜单")
                    {
                        if (subNode.ChildNodes.Count == 0) continue;

                        ButtonItem btn = new ButtonItem();
                        btn.AutoCollapseOnClick = true;
                        btn.AutoExpandOnClick = true;
                        btn.Text = subNode.Attributes["名称"].Value.ToString();
                        XmlNodeList nodelist2 = subNode.ChildNodes;
                        foreach (XmlElement subNode2 in nodelist2)
                        {
                            if (subNode2.Name == "功能点")
                            {
                                Type elementType = Type.GetType(subNode2.Attributes["typename"].Value);
                                if (elementType == null) continue;
                                object elementObj = Activator.CreateInstance(elementType);
                                BaseItem item = (_Application as IFramework).BarManager.CommandPoolEx.FindBaseItem(elementObj.ToString());
                                if (item == null) continue;
                                if (item is ButtonItem)
                                {
                                    BaseItem item2 = item.Copy();
                                    (item2 as ButtonItem).ButtonStyle = DevComponents.DotNetBar.eButtonStyle.Default;
                                    (item2 as ButtonItem).ImagePosition = DevComponents.DotNetBar.eImagePosition.Left;
                                    (item2 as ButtonItem).ImageFixedSize = new Size(18, 18);
                                    btn.SubItems.Add(item2);
                                }
                            }
                        }
                        ribbonControl1.QuickToolbarItems.Add(btn);
                    }
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 保存快速布局
        /// </summary>
        private void SaveLayoutConfig()
        {
            try
            {
                string strFile = AppConfig.ConfigPath + "\\LayoutConfig.xml";
                XmlDocument doc = new XmlDocument();
                if (File.Exists(strFile) == false)
                {
                    if (ribbonControl1.QuickToolbarItems.Count == 0) return;
                    else
                        doc.LoadXml("<LayoutConfig>	<SelectedTabItem/>	<QuickAccessItems/></LayoutConfig>");
                }
                else
                    doc.Load(strFile);
                XmlNode node = doc.SelectSingleNode("//SelectedTabItem");
                if (node != null)
                    node.InnerText = ribbonControl1.SelectedRibbonTabItem.Text;
                node = doc.SelectSingleNode("//QuickAccessItems");
                node.RemoveAll();
                foreach (BaseItem baseItem in ribbonControl1.QuickToolbarItems)
                {
                    if (baseItem is Office2007StartButton) continue;
                    if (baseItem is QatCustomizeItem) continue;
                    if (baseItem is SystemCaptionItem) continue;
                    if (baseItem is ButtonItem && baseItem.Tag is ESRI.ArcGIS.SystemUI.ICommand)
                    {
                        XmlNode subNode = doc.CreateElement("功能点");
                        XmlAttribute att = doc.CreateAttribute("名称");
                        att.Value = baseItem.Text;
                        XmlAttribute att2 = doc.CreateAttribute("typename");
                        att2.Value = baseItem.Tag.GetType().AssemblyQualifiedName;
                        subNode.Attributes.Append(att);
                        subNode.Attributes.Append(att2);
                        node.AppendChild(subNode);
                    }
                }
                doc.Save(strFile);
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteErrorText(ex);
            }
        }

        /// <summary>
        /// 工具条自动隐藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dotNetBarManager1_AutoHideChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTabIndex == 0)
            {
                m_MapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, m_MapControl.ActiveView.Extent);
            }
            else if (tabControl1.SelectedTabIndex == 1)
            {
                m_PageLayoutControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, m_PageLayoutControl.ActiveView.Extent);
            }

        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuPSD_Click(object sender, EventArgs e)
        {
            FrmUpdatePSD frm = new FrmUpdatePSD();
            frm.ShowDialog(this);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuUpUser_Click(object sender, EventArgs e)
        {
            FrmUserInfo frm = new FrmUserInfo();
            frm.ShowDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainFramework_Resize(object sender, EventArgs e)
        {
            SetSecurityLoaction();            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainFramework_LocationChanged(object sender, EventArgs e)
        {
            SetSecurityLoaction();
        }
        /// <summary>
        /// 
        /// </summary>
        private void SetSecurityLoaction()
        {
            if (frmSecurity != null)
            {
                frmSecurity.Location = new System.Drawing.Point(this.Location.X + this.Width - frmSecurity.Width - 30, this.Location.Y + ribbonControl1.Height - frmSecurity.Height - 30);
            }
        }

    }
}
   